import baostock as bs
import pandas as pd
import sys
import warnings
warnings.filterwarnings('ignore')
def simulate():
    code = sys.argv[2]
    begin_day = sys.argv[3]
    end_day = sys.argv[4]
    add_interval = float(sys.argv[5])
    increase = float(sys.argv[6])
    subtract_interval = float(sys.argv[7])
    reduction = float(sys.argv[8])
    next_add_interval = float(sys.argv[9])
    next_increase = float(sys.argv[10])
    print('begin_day: ' , begin_day)
    print('add_interval: ' , add_interval, '%')
    print('subtract_interval: ' , subtract_interval, '%')
    print('reduction: ' , reduction, '%')
    print('increase: ' , increase)
    data = pd.read_table(code + ".csv",sep=",",header=0)
    print (data.loc[1])
    price = next_buy_price =0
    all_number = all_money = begin = 0
    result_list = []
    sale_list=pd.DataFrame(columns=['sale_price','sale_number'])
    for indexs in data.index:
        date = data.loc[indexs].values[0]
        high = data.loc[indexs].values[2]
        low = data.loc[indexs].values[3]
        if date == end_day:
            break
        if not begin:
            if (begin_day == date):
                begin = 1
                print(data.loc[indexs].values[0])
                price = begin_price = high
                next_buy_price = price * (1 - add_interval * 0.01)
                next_buy_price = float('%.2f' % next_buy_price)
                buy_number = 1
                all_number += buy_number
                money = int(price * buy_number * 100)
                all_money += money
                sale_price = begin_price * 1.5
                sale_price = float('%.2f' % sale_price)
                sale_number = 1
                print('date', date, 'price: ' , price, 'next_buy_price: ' , next_buy_price, 'spend money: ', money, 'sale_price: ', sale_price, 'sale_number', sale_number)
                new=pd.DataFrame({'sale_price':sale_price,
                 'sale_number':sale_number
                 },index=[0]
                )
                sale_list=sale_list.append(new,ignore_index=True)
                list1 = [date,begin_price,buy_number,money,next_buy_price,sale_price,sale_number,all_money,price]
                result_list.append(list1)
                print(sale_list)
                continue
        # 买入点执行买入
        if date != end_day and next_buy_price <= high and next_buy_price >= low:
            price = next_buy_price
            buy_number = buy_number * int(increase)
            print('buy_number',buy_number)
            money = int(price * buy_number * 100)
            all_number += buy_number
            all_money += money
            avd = all_money / (100 * all_number)
            avd = float('%.2f' % avd)
            sale_price = price * (1 + subtract_interval * 0.01)
            sale_price = float('%.2f' % sale_price)
            sale_number = int(buy_number * (reduction * 0.01))
            next_buy_price = price * (1 - add_interval * 0.01)
            next_buy_price = float('%.2f' % next_buy_price)
            print('date', date, 'price: ' , price, 'next_buy_price: ' , next_buy_price,'buy_number', buy_number,  'spend money: ', money, 'sale_price: ', sale_price, 'sale_number', sale_number,'all_number',all_number, 'all_money', all_money, 'avd', avd)
            list1 = [date,price,buy_number,money,next_buy_price,sale_price,sale_number,all_money,avd]
            result_list.append(list1)
            new=pd.DataFrame({'sale_price':sale_price,
                 'sale_number':sale_number
                 },index=[0]
                )
            sale_list=sale_list.append(new,ignore_index=True)
            print(sale_list)
            continue #一天内如果买入就不卖出
        # 遍历卖出点,执行减仓
        for index,row in sale_list.iterrows():
            sale_price = row['sale_price']
            if date != end_day and sale_price <= high and sale_price >= low:
                # print(sale_price, 'low: ', low, 'index', index)
                next_buy_price = sale_price * (1 - next_add_interval * 0.01)
                next_buy_price = float('%.2f' % next_buy_price)
                sale_number = int(row['sale_number'])
                buy_number = buy_number / int(increase) * int(next_increase)
                print('--buy_number',buy_number,'all_number',all_number,'sale_number',sale_number)
                money = int(sale_price * sale_number * 100)
                all_number = all_number - sale_number
                all_money = all_money - money
                avd = all_money / (100 * all_number)
                avd = float('%.2f' % avd)
                print('date', date, 'sale_price: ' , sale_price, 'next_buy_price: ' ,next_buy_price,'sale_number',-sale_number, 'buy_number', buy_number, 'get money: ', money, 'all_number',all_number,'all_money', all_money,  'avd', avd)
                list1 = [date,sale_price,-sale_number,-money,next_buy_price,0,0,all_money,avd]
                result_list.append(list1)
                print(sale_list)
                sale_list=sale_list.drop(index)
                print(sale_list)
    result = pd.DataFrame(result_list, columns=['日期','价格','买入份数','花费金额','下次买入价','卖出点','下次卖出份数','花费总金额','平均成本'])
    result.to_csv("./result.csv", encoding="utf-8", index=False)
def download():
    code = sys.argv[2]
    begin_day = sys.argv[3]
    end_day = sys.argv[4]
    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    # print(lg.error_code)
    # print(lg.error_msg)
    # 详细指标参数，参见“历史行情指标参数”章节
    rs = bs.query_history_k_data(code,
                "date,code,high,low",
                    start_date='2021-01-01', end_date='2022-12-02',
                        frequency="d", adjustflag="3")
    # 获取具体的信息
    result_list = []
    while (rs.error_code == '0') & rs.next():
        # 分页查询，将每页信息合并在一起
        result_list.append(rs.get_row_data())
    result = pd.DataFrame(result_list, columns=rs.fields)
    result.to_csv(code + ".csv", encoding="utf-8", index=False)
    bs.logout()
if __name__ == "__main__":
    print('参数列表:', str(sys.argv))
    print('脚本名为：', sys.argv[0])
    for i in range(1, len(sys.argv)):
        print('参数 %s 为：%s' % (i, sys.argv[i]))
    if sys.argv[1] == 'download':
        download()
    if sys.argv[1] == 'simulate':
        simulate()
        code = sys.argv[2]
        begin_day = sys.argv[3]
        end_day = sys.argv[4]
        add_interval = float(sys.argv[5])
        increase = float(sys.argv[6])
        subtract_interval = float(sys.argv[7])
        reduction = float(sys.argv[8])
        next_add_interval = float(sys.argv[9])
        next_increase = float(sys.argv[10])
        print('code',code,'begin_day: ' , begin_day,'end_day',end_day)
        print('add_interval 跌幅（加仓间隔）: ' , add_interval, '%')
        print('subtract_interval 涨幅（减仓间隔）: ' , subtract_interval, '%')
        print('reduction 减仓比例: ' , reduction, '%')
        print('increase 加仓倍数: ' , increase, '倍')
        print('next_add_interval 减仓后跌幅（加仓间隔）: ' , next_add_interval, '%')
        print('next_increase 减仓后加仓倍数: ' , next_increase, '倍')